//
//  EventListViewController.m
//  Runone
//
//  Created by runone02 on 16/12/5.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "EventListViewController.h"
#import "MJExtension.h"
#import "AppDelegate.h"
#import "MJRefresh.h"
#import "RequestGinsengModel.h"
#import "CurrentEvent.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "SVProgressHUD.h"
#import "ParModel.h"
#import "RightCodeTool.h"
#import "TollEvent.h"
#import "AppConstants.h"
#import "AppLocalManager.h"
#import "EventBaseCell.h"
#import "CurrentContructDetailViewController.h"
#import "CurrentIncidentDetailViewController.h"
#import "HistoryInidentDetailController.h"
#import "HistoryConstructDetailController.h"
#import "TollStationEventDetailController.h"
#import "ROTitleDispalyHeader.h"
#import "RightCodeTool.h"
#import "InprogressController.h"
#import "UnStartEventController.h"

#define PageSize  10
@interface EventListViewController () <UINavigationBarDelegate>

@property (nonatomic, strong) NSString *loadMoreMethodName;

@end

static NSString *cellID = @"historyCell";
@implementation EventListViewController

#pragma     事件管理      施工事件

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = kTableViewCellTextColor;
    _page          = 0;
    self.dataArray = [[NSMutableArray alloc] init];
    [self judgeLoadMoreMethodName];
    
    self.view.backgroundColor            = [UIColor whiteColor];
    self.tableView.contentInset          = UIEdgeInsetsMake(1, 0, 50, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    [self.tableView registerNib:[UINib nibWithNibName:@"EventBaseCell" bundle:nil] forCellReuseIdentifier:cellID];
    self.tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
    [self fetchNewServer];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.tableView.mj_footer.hidden = YES;
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
RegisterNotify(GLConstructEventReportNotification, @selector(requestAgain));
}

- (void) requestAgain {
    [self fetchNewServer ];
}
-(void)dealloc {
    RemoveNofify
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
       // [self fetchNewServer]; GLConstructEventReportNotification
    //    [self setNavigationBar];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //    self.tabBarController.tabBar.hidden = YES;
}


-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
   // [self fetchNewServer];
}


#pragma mark - 下拉
-(void)loadNewData {
    
    [self fetchNewServer];
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

- (void) judgeLoadMoreMethodName {
    if (_titleType == 4) { //施工事件
        _loadMoreMethodName = @"GetAllConstructEventByPage";
        
    }
}
#pragma       加载数据
-(void)loadMoreData {
    [self fetchMoreServer];
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

- (void)fetchNewServer {
    
    self.page = 1;
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getAllModel=[[RequestGinsengModel alloc] init];
    getAllModel.URL         = GetEventDataURL;
    //    getAllModel.DataValue   = [self DataValueEventUId:nil pageString:@"0" andSizeString:@"10"];
    
    
    getAllModel.DataValue   = [self DataValueEventUId:nil pageString:@"0" andSizeString:@"10"];
    getAllModel.UpdatedTime = @"";
    getAllModel.SystemCode  = @"GuangleHighway";
    getAllModel.MethodName  = _methodName; //@"GetAllHistoryEventByPage"
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel) {
        
        
        _dataArray = [CurrentEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
        
        [self.tableView reloadData];
    };
    [requestHelper RequestGinsengModel:getAllModel andPushController:self];
}
- (void)fetchMoreServer {
    _page  += 1;
    NSString *pageStr  = [NSString stringWithFormat:@"%ld",(long)_page];
    NSString *pageSize = [NSString stringWithFormat:@"%d",PageSize];
    
    RequestHelper *requestHelper   = [[RequestHelper alloc] init];
    RequestGinsengModel *getByPage = [[RequestGinsengModel alloc] init];
    getByPage.URL         = GetEventDataURL;
    
    CurrentEvent *lasetModel = [self.dataArray lastObject];
    getByPage.DataValue   = [self DataValueEventUId:lasetModel.IncidentUID pageString:pageStr andSizeString:pageSize];
        
    getByPage.UpdatedTime = @"";
    getByPage.SystemCode  = @"GuangleHighway";
    getByPage.MethodName  = _loadMoreMethodName;
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        //        NSLog(@"%@",requestOutginseng.DataValue);
        if ([requestOutginseng.Code isEqualToString:@"001"]) {
            NSArray *tempArray = [[NSArray alloc] init];
            
            
            tempArray = [CurrentEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
            
            if (tempArray.count == 0) {
                self.page -= 1;
                [SVProgressHUD showSuccessWithStatus:@"没有更多的数据了"];
            }
            
            if (tempArray.count > 1) {
                [self.dataArray addObjectsFromArray:tempArray];
                [self.tableView reloadData];
            }
        }else {
            self.page -= 1;
        }
    };
    [requestHelper RequestGinsengModel:getByPage andPushController:self];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EventBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    cell.backgroundColor = kViewBackGroundColor;
    CurrentEvent *model = self.dataArray[indexPath.row];
    
    cell.markInt = EventListTitleTypeConstruct;
    
    cell.ceModel = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CurrentEvent *model = [_dataArray objectAtIndex:indexPath.row];
    CGFloat cellH;
    CGFloat height;
    if ((model.DealDetail)) {
        NSString *tempStr = model.DealDetail;
        cellH = [self caculateCellHeight:tempStr];
        int colun = cellH / 16; // 校准
        if (colun == 1) {
            height = 110;
        }else {
            height = cellH + 16 + 44 + 5 + 20 + 8 + colun * 0.293;
        }
    }else {
        height = 110;
    }
    return height;
    
}

#pragma mark - 计算cell的高度
- (CGFloat) caculateCellHeight:(NSString *)string  {
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGSize maxSize   = CGSizeMake([UIScreen mainScreen].bounds.size.width - 68, MAXFLOAT);
    CGFloat dealHeight = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:attributes context:nil].size.height;
    return dealHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_titleType == EventListTitleTypeConstruct) { //施工事件
        CurrentEvent *model = _dataArray[indexPath.row];
        NSString *str     = [[AppLocalManager sharedManager] getDataByKey:SYSUSERUID];
        if ([model.RecordUserUID isEqualToString:str]) {
            if (model.State == 1) { // 未开始
                if ([[RightCodeTool sharedTool] rightIsEqualTO:@"P040401"]) {                    UnStartEventController *vc = [[UnStartEventController alloc] init];
                    vc.reportModel              = model;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
            if (model.State == 2) { // 进行中
                if ([[RightCodeTool sharedTool] rightIsEqualTO:@"P040402"]) {
                    InprogressController *vc = [[InprogressController alloc]init];
                    vc.reportModel               = model;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
        } else {
            [SVProgressHUD showSuccessWithStatus:@"不能编辑他人事件"];
            return;
        }
    }
}

#pragma mark - 拼接参数
-(NSString *)DataValueEventUId:(NSString *)eventUID pageString:(NSString *)pageStr andSizeString:(NSString *)sizeStr {
    NSString *valueStr =[NSString stringWithFormat:                           @"[{\"key\":\"LastEventUID\",\"value\":\"%@\"},                                                      {\"key\":\"PageIndex\",\"value\":\"%@\"},                               {\"key\":\"PageSize\",\"value\":\"%@\"}]",eventUID,pageStr,sizeStr];
    
    return valueStr;
}




@end
